﻿using Giant.Core;
using Giant.Plugin.Widgets.BaiduAnalytics.Models;
using Giant.Services.Configuration;
using Giant.Services.Localization;
using Giant.Services.Logging;
using Giant.Services.Sites;
using Giant.Web.Framework.Controllers;
using System;
using System.Web.Mvc;

namespace Giant.Plugin.Widgets.BaiduAnalytics.Controllers
{
    public class WidgetBaiduAnalyticsController: BasePluginController
    {
        private readonly IWorkContext _workContext;
        private readonly ISiteContext _siteContext;
        private readonly ISiteService _siteService;
        private readonly ISettingService _settingService;
        private readonly ILogger _logger;
        private readonly ILocalizationService _localizationService;

        public WidgetBaiduAnalyticsController(IWorkContext workContext,
            ISiteContext siteContext,
            ISiteService siteService,
            ISettingService settingService,
            ILogger logger,
            ILocalizationService localizationService)
        {
            this._workContext = workContext;
            this._siteContext = siteContext;
            this._siteService = siteService;
            this._settingService = settingService;
            this._logger = logger;
            this._localizationService = localizationService;
        }

        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult Configure()
        {
            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var googleAnalyticsSettings = _settingService.LoadSetting<BaiduAnalyticsSettings>(siteScope);
            var model = new ConfigurationModel();
            model.TrackingScript = googleAnalyticsSettings.TrackingScript;
            model.ZoneId = googleAnalyticsSettings.WidgetZone;
            model.AvailableZones.Add(new SelectListItem() { Text = "Head html tag", Value = "head_html_tag" });

            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {   
                model.TrackingScript_OverrideForSite = _settingService.SettingExists(googleAnalyticsSettings, x => x.TrackingScript, siteScope);                
                model.ZoneId_OverrideForSite = _settingService.SettingExists(googleAnalyticsSettings, x => x.WidgetZone, siteScope);
            }

            return View("~/Plugins/Widgets.BaiduAnalytics/Views/WidgetsBaiduAnalytics/Configure.cshtml", model);
        }

        [HttpPost]
        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult Configure(ConfigurationModel model)
        {
            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var analyticsSettings = _settingService.LoadSetting<BaiduAnalyticsSettings>(siteScope);
            analyticsSettings.TrackingScript = model.TrackingScript;
            analyticsSettings.WidgetZone = model.ZoneId;

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerSite(analyticsSettings, x => x.TrackingScript, model.TrackingScript_OverrideForSite, siteScope, false);
            _settingService.SaveSettingOverridablePerSite(analyticsSettings, x => x.WidgetZone, model.ZoneId_OverrideForSite, siteScope, false);

            //now clear settings cache
            _settingService.ClearCache();

            SuccessNotification(_localizationService.GetResource("Admin.Plugins.Saved"));

            return Configure();
        }

        [ChildActionOnly]
        public ActionResult PublicInfo(string widgetZone, object additionalData = null)
        {
            string globalScript = "";
            var routeData = ((System.Web.UI.Page)this.HttpContext.CurrentHandler).RouteData;

            try
            {
                var controller = routeData.Values["controller"];
                var action = routeData.Values["action"];

                if (controller == null || action == null)
                    return Content("");

                globalScript += GetTrackingScript();

            }
            catch (Exception ex)
            {
                _logger.InsertLog(Core.Domain.Logging.LogLevel.Error, "Error creating scripts for baidu tracking", ex.ToString());
            }
            return Content(globalScript);
        }

        private string GetTrackingScript()
        {
            var analyticsSettings = _settingService.LoadSetting<BaiduAnalyticsSettings>(_siteContext.CurrentSite.Id);
            var analyticsTrackingScript = analyticsSettings.TrackingScript + "\n";
            return analyticsTrackingScript;
        }
    }
}
